const fs = require('fs');
const axios = require('axios')
const ProgressBar = require('progress');

const textFilePath = './data.txt';
const jsonFilePath = './output.json';


function delay(duration) {
    return new Promise(resolve => setTimeout(resolve, duration));
}

// 读取文本文件内容
fs.readFile(textFilePath, 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading the text file: ', err);
        return;
    }

    // 将数据按行分割
    const lines = data.split('\n');
    const bar = new ProgressBar(':bar :percent', { total: lines.length });
    let jsonResult = {};

    // 异步遍历和翻译每一行
    let lineCount = 0;
    lines.forEach(async (line) => {
        if (line.trim()) {
            // 翻译每一行

            var data = {
                from: "en",
                to: "zh",
                q: line
            };

            var config = {
                method: 'post',
                url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=24.8c0a3bba3cfc19edf32c31d3aa15fdb1.2592000.1707327005.282335-46686141',
                data: data
            };

            await axios(config)
                .then(function (response) {
                    if (response.data && response.data.result && response.data.result.trans_result && response.data.result.trans_result[0].dst) {
                        console.log(line + " => " + response.data.result.trans_result[0].dst);
                        // 将翻译后的文本添加到JSON对象
                        jsonResult[line] = {
                            translate: response.data.result.trans_result[0].dst,
                            key: line
                        };

                        // 更新进度条
                        bar.tick();

                        if (++lineCount === lines.length) {
                            // 所有行处理完毕，写入JSON文件
                            fs.writeFile(jsonFilePath, JSON.stringify(jsonResult, null, 2), (err) => {
                                if (err) {
                                    console.error('Error writing the JSON file: ', err);
                                } else {
                                    console.log('JSON file was created successfully.');
                                }
                            });
                        }
                    }
                })
                .catch(function (error) {
                    console.error('Error translating line: ', error);
                    lineCount++;
                });
        } else {
            lineCount++;
        }
    });
});
